package com.xbongbong.saas.help;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasAppEntity;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.EnableEnum;
import com.xbongbong.paas.model.PaasAppModel;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.app.pojo.vo.ApplicationVO;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.constant.RangeScreenConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.menu.enums.SystemAppMenuEnum;
import com.xbongbong.pro.knowledge.base.pojo.OptionalRangePojo;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.domain.entity.SharePermissionSetUserEntity;
import com.xbongbong.sys.model.SharePermissionSetUserModel;
import org.apache.tomcat.util.buf.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author 李翔
 * @date 2023/2/28
 * @description
 */
@Component
public class SharePermissionHelper {

    @Resource
    private SharePermissionSetUserModel sharePermissionSetUserModel;
    @Resource
    private PaasAppModel paasAppModel;

    /**
     * 拼接过滤条件
     * @param corpid
     * @param appId
     * @param formId
     * @param nameLike
     * @param rangeScreen
     * @return
     * @throws XbbException
     */
    public Map<String, Object> getFilterMap(String corpid, Long appId, Long formId, String nameLike, JSONObject rangeScreen) throws XbbException {
        Map<String, Object> filterMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        filterMap.put(ParameterConstant.CORPID, corpid);
        filterMap.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        filterMap.put(ParameterConstant.ORDER_BY_STR, "add_time DESC");
        if (Objects.nonNull(appId)) {
            filterMap.put("appId", appId);
        }
        if (Objects.nonNull(formId)) {
            filterMap.put("formId", formId);
        }
        if (StringUtil.isNotEmpty(nameLike)) {
            filterMap.put("nameLike", nameLike);
        }
        if (Objects.nonNull(rangeScreen) && Objects.nonNull(rangeScreen.get(RangeScreenConstant.PROPERTY))
                && StringUtil.isNotEmpty(rangeScreen.getString(RangeScreenConstant.PROPERTY))
                && Objects.nonNull(rangeScreen.get(RangeScreenConstant.ID))) {
            String property;
            String id;
            try {
                property = rangeScreen.getString(RangeScreenConstant.PROPERTY);
                id = rangeScreen.getString(RangeScreenConstant.ID);
            } catch (Exception e) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001.getCode(), "SharePermissionHelper.getFilterMap中的rangeScreen参数错误");
            }
            if (Objects.equals(property, RangeScreenConstant.DEPT)) {
                filterMap.put("depId", id);
            } else if (Objects.equals(property, RangeScreenConstant.ROLE)) {
                filterMap.put("roleId", id);
            } else {
                filterMap.put("userId", id);
                List<SharePermissionSetUserEntity> entitys = sharePermissionSetUserModel.findEntitys(filterMap);
                List<Long> shareRuleIdIn = new ArrayList<>();
                for (SharePermissionSetUserEntity entity : entitys) {
                    shareRuleIdIn.add(entity.getShareRuleId());
                }
                filterMap.remove("userId");
                if (!shareRuleIdIn.isEmpty()) {
                    filterMap.put("idIn", shareRuleIdIn);
                } else {
                    filterMap.put("idIn", Collections.singletonList(-1));
                }
            }
        }
        return filterMap;
    }

    /**
     * 获取授权人员Str 前端回显用
     * @param authorityArray
     * @param authorityUser
     * @param userNameMap
     * @return
     */
    public String getAuthorityNameStr(JSONArray authorityArray, JSONArray authorityUser, Map<String, String> userNameMap) {
        String res = "";
        if (Objects.isNull(authorityArray) || authorityArray.isEmpty()) {
            return res;
        }
        List<OptionalRangePojo> optionalRangePojos = JSONArray.parseArray(authorityArray.toJSONString(), OptionalRangePojo.class);
        List<String> nameList = new ArrayList<>();
        for (OptionalRangePojo item : optionalRangePojos) {
            if (Objects.equals(item.getProperty(), RangeScreenConstant.DEPT)) {
                nameList.add(item.getName() + I18nMessageUtil.getMessage(I18nStringConstant.DEPARTMENT_SHOW));
            } else if (Objects.equals(item.getProperty(), RangeScreenConstant.ROLE)) {
                nameList.add(item.getName() + I18nMessageUtil.getMessage(I18nStringConstant.ROLE_SHOW));
            }
        }

        List<String> userIds = JSONArray.parseArray(JSON.toJSONString(authorityUser), String.class);
        userIds.stream().map(userId -> userNameMap.getOrDefault(userId, "Unknown") +  I18nMessageUtil.getMessage(I18nStringConstant.EMPLOYEE_SHOW))
                .forEach(nameList::add);
        return StringUtils.join(nameList, '、');
    }

    /**
     * 开启的并且可支持的 应用列表
     * @param corpid
     * @return
     */
    public List<ApplicationVO> getEnableAppList(String corpid) {
        List<ApplicationVO> res = new ArrayList<>();

        Map<String, Object> params = new HashMap<>();
        params.put("corpid", corpid);
        params.put("enable", EnableEnum.OPEN.getCode());
        params.put("del", DelEnum.NORMAL.getDel());
        List<PaasAppEntity> enableAppList = paasAppModel.findEntitys(params);
        if (enableAppList.isEmpty()) {
            return res;
        }
        for (PaasAppEntity paasAppEntity : enableAppList) {
            String alias = paasAppEntity.getAlias();
            SystemAppMenuEnum systemAppMenuEnum = SystemAppMenuEnum.getSystemAppMenuEnum(alias);
            if (Objects.nonNull(systemAppMenuEnum)) {
                switch (systemAppMenuEnum) {
                    case CRM:
                    case PRODUCT:
                    case JXC:
                    case FUND_MANAGEMENT:
                    case MARKET_MANAGEMENT:
                        ApplicationVO applicationVO = new ApplicationVO();
                        BeanUtil.copyProperties(paasAppEntity, applicationVO);
                        res.add(applicationVO);
                        continue;
                    case BUNDLE:
                    case DISTRIBUTOR:
                    case MARKETING_MANAGEMENT:
                    case ORDER_CENTER:
                    case FINE_CLUE:
                    case CONTRACT_COMPARE:
                    case EXPENSE_MANAGEMENT:
                    case ESIGN:
                    case WORK_ORDER:
                    case WORK_ORDER_V2_CENTER:
                    case CALL_CENTER:
                    case CALL_CENTER_DU_YAN:
                    case GROUP_MESSAGE:
                    case SEARCH_CUSTOMER:
                    case COOL_APP:
                    default:
                }
            } else {
                ApplicationVO applicationVO = new ApplicationVO();
                BeanUtil.copyProperties(paasAppEntity, applicationVO);
                res.add(applicationVO);
            }

        }
        return res;
    }
}
